package com.helloandroid.tools

import com.github.salomonbrys.kotson.*
import com.google.gson.*
import com.helloandroid.models.*
import com.helloandroid.vo.MatchState
import com.helloandroid.vo.MatchType
import com.helloandroid.vo.UserMatchState
import org.junit.Test
import java.lang.RuntimeException

data class TestMatch(val name:String,val type: MatchType)

fun fakeMatch():Pair<ArrayList<Match>,ArrayList<Match>>{
    val sysTime = System.currentTimeMillis()

    val lst3000 = ArrayList<Match>()
    val lst8000 = ArrayList<Match>()

    // 返回一共9条数据
    var beginTimeMs = sysTime - 7 * 24 * 3600 * 1000
    for(i in 1..9){
        val timeStamp = MyTimeUtils.dayTimeString(beginTimeMs)
        val totalMoney1 = (Math.random() * 500 + 500).toInt()
        val totalPeople1 = (Math.random() * 100 + 100).toInt()


        val totalMoney2 = (Math.random() * 500 + 500).toInt()
        val totalPeople2 = (Math.random() * 100 + 100).toInt()

        when(i){
            8 -> {
                lst3000.add(Match(MatchType.M3000,i,totalMoney1,totalPeople1,timeStamp, MatchState.Running))
                lst8000.add(Match(MatchType.M8000,i,totalMoney2,totalPeople2,timeStamp, MatchState.Running))
            }
            9-> {
                lst3000.add(Match(MatchType.M3000,i,totalMoney1,totalPeople1,timeStamp, MatchState.Unstarted))
                lst8000.add(Match(MatchType.M8000,i,totalMoney2,totalPeople2,timeStamp, MatchState.Unstarted))
            }
            else -> {
                lst3000.add(Match(MatchType.M3000,i,totalMoney1,totalPeople1,timeStamp, MatchState.Ended))
                lst8000.add(Match(MatchType.M8000,i,totalMoney2,totalPeople2,timeStamp, MatchState.Ended))
            }
        }

        beginTimeMs -= 24 * 3600 * 1000
    }
    return Pair(lst3000,lst8000)
}
fun fakeRelatedMatch(arr:List<Match>):ArrayList<RelatedMatch>{
    val relatedLst = ArrayList<RelatedMatch>()
    val num = (Math.random() * 3 + 2).toInt()

    // 挑选几个索引
    var idxLst = generateSequence(0){it + 1}
            .takeWhile { it < arr.size }
            .shuffled()
            .filterIndexed { index, _ -> index < num  }
            .toList()

    idxLst.forEach {
        val match = arr[it]

        // 如果是今天,则是进行中
        // 如果是明天, 则是还未开始进行
        when(it){
            7 ->  relatedLst.add(RelatedMatch(match.matchId, UserMatchState.Moving))
            8 ->  relatedLst.add(RelatedMatch(match.matchId, UserMatchState.TakePart))
            else -> {
                val userState = setOf<UserMatchState>(UserMatchState.UnComplete, UserMatchState.Completed, UserMatchState.Geted).random()
                relatedLst.add(RelatedMatch(match.matchId,userState))
            }
        }
    }
    return relatedLst
}

class testCustomGson {

    @Test
    fun buildEnum(){
        val match1 = TestMatch("比赛1",MatchType.M8000)

        // 自定义 序列化
        val gson = GsonBuilder().registerTypeAdapter<MatchType>(){
            serialize {
                JsonPrimitive(it.src.value)
            }
            deserialize {
                when(val value = it.json.asInt){
                    1->MatchType.M3000
                    2->MatchType.M8000
                    else->throw RuntimeException("unknow value:$value")
                }
            }
        }.create()
        val str = gson.toJson(match1)
                // jsonObject("match" to match1)
        println("str:\n$str")
        println("准备转换成obj:")

        val obj1 = gson.fromJson<TestMatch>(str)
        println("XXX：\n ${obj1}")
    }

    @Test
    fun buildMoreData(){
        val pair = fakeMatch()
        val m3Lst = pair.first
        val m8Lst = pair.second

        val m3Related = fakeRelatedMatch(m3Lst)
        val m8Related = fakeRelatedMatch(m8Lst)

        val m3 = MatchData(m3Lst,m3Related)
        val m8 = MatchData(m8Lst,m8Related)

        val gson = GsonBuilder().registerTypeAdapter<MatchType>{
            serialize {
                JsonPrimitive(it.src.value)
            }
            deserialize {
                when(val value = it.json.asInt){
                    1->MatchType.M3000
                    2->MatchType.M8000
                    else->throw RuntimeException("unknow value:$value")
                }
            }
        }.registerTypeAdapter<UserMatchState>{
            serialize {
                JsonPrimitive(it.src.value)
            }
            deserialize {
                when(val value = it.json.asInt){
                    0-> UserMatchState.TakePart
                    1-> UserMatchState.Moving
                    2-> UserMatchState.UnComplete
                    3-> UserMatchState.Completed
                    4->UserMatchState.Geted
                    else->throw RuntimeException("unknow value:$value")
                }
            }
        }.registerTypeAdapter<MatchState>{
            serialize {
                JsonPrimitive(it.src.value)
            }
            deserialize {
                when(val value = it.json.asInt){
                    1-> MatchState.Unstarted
                    2-> MatchState.Running
                    3-> MatchState.Ended
                    else->throw RuntimeException("unknow value:$value")
                }
            }
        }.create()

//        gson.toJson()
//        jsonObject()

        val str = jsonObject(
                "err" to 0,
                "data" to jsonObject(
                        "m3000" to gson.toJson(m3),
                        "m8000" to gson.toJson(m8)
                )
        )

        println("str:\n $str")

        //
        println("=============准备开始解析....")

        val dataJsonObj = (Gson().fromJson(str) as JsonElement).asJsonObject.get("data")
        val pm3 = gson.fromJson<MatchData>(dataJsonObj.get("m3000").asString)
        val pm8 = gson.fromJson<MatchData>(dataJsonObj.get("m8000").asString)
        println("pm3:$pm3")
        println("pm8:$pm8")
    }

}